<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\adminapi\controller;

use app\adminapi\library\Auth;
use app\adminapi\validate\Login;
use app\common\controller\BackendApi;
use think\Hook;

/**
 * 后台首页
 * @internal
 */
class Index extends BackendApi
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['index', 'logout','menu'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        $auth = Auth::instance();
        $result = $auth->getRuleList($this->auth->getAdminId());
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        if ($this->auth->isLogin()) {
            $this->success('您已登陆');
        }

        $username = $this->request->post('username');
        $password = $this->request->post('password', '', null);

        $loginValidate = new Login();
        if (!$loginValidate->check(['username'=>$username, 'password'=>$password])){
            $this->error($loginValidate->getError());
        }

        $result = $this->auth->login($username, $password);
        if ($result === true) {
            Hook::listen("admin_login_after", $this->request);
            $this->success('登陆成功',['userinfo'=>$this->auth->getAdminInfo()]);
        } else {
            $msg = $this->auth->getError();
            $msg = $msg ? $msg : __('Username or password is incorrect');
            $this->error($msg, ['token' => $this->request->token()]);
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        if ($this->auth->getError()){
            $this->error($this->auth->getError());
        }
        Hook::listen("admin_logout_after", $this->request);
        $this->success(__('Logout successful'));
    }

    public function menu()
    {
        $data = $this->auth->getMenu();
        $this->success('获取成功', $data);
    }

}
